package com.ruoyi.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.stripe.Stripe;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.exception.StripeException;
import com.stripe.model.Event;
import com.stripe.model.PaymentIntent;
import com.stripe.net.Webhook;
import com.stripe.param.PaymentIntentCreateParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;


@RestController
@RequestMapping(value = "/pay")
@Slf4j
public class PayController {
    @PostMapping(value = "/create")
    public String createOrder(BigDecimal flowPrice, String orderSn, int type) throws StripeException {
        Stripe.apiKey = "sk_test_51QTlHxP4lwFAbG69sSsM9wL2br24lW3tOB8uPcuuS6ojWTYKnUile701KxI7hXSD5DZw11gQNLtoIVEvDj5EzRPi00E6gF4Kt9";
        //此处传入自己的订单需要自定义的参数
        HashMap<String, String> map = new HashMap<>();
        map.put("order_sn", orderSn);
        map.put("order_type", String.valueOf(type));
        long longValue = flowPrice.multiply(new BigDecimal(100)).longValue();
        PaymentIntentCreateParams params = PaymentIntentCreateParams.builder().setAutomaticPaymentMethods(PaymentIntentCreateParams.AutomaticPaymentMethods.builder().setEnabled(true).build()).setCurrency("USD") //设置金额类型，此处为美元
                .setAmount(longValue) //设置金额，按分结算
                .putAllMetadata(map)  //添加自定义的参数
                .build();
        // Create a PaymentIntent with the order amount and currency
        PaymentIntent intent = PaymentIntent.create(params);
        JSONObject entries = JSONUtil.parseObj(intent);
        log.info(entries.toString());
        // Send PaymentIntent details to client
        return intent.getClientSecret();
    }

    @PostMapping("/callback")
    public void callback(HttpServletRequest request) throws IOException {
        String payload = readPayload(request);
        String sigHeader = request.getHeader("Stripe-Signature");
        String endpointSecret = "whsec_nW9GDjT5py6XItZ5cMwNXjIFvn0aAknt";

        try {
            Event event = Webhook.constructEvent(payload, sigHeader, endpointSecret);
            handleEvent(event);
        } catch (SignatureVerificationException e) {
            log.error("Stripe signature verification failed: {}", e.getMessage());
            // 适当的错误处理逻辑
        }
    }

    private String readPayload(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    private void handleEvent(Event event) {
        // 根据事件类型处理事件
        switch (event.getType()) {
            case "payment_intent.succeeded":
                // 支付成功的逻辑
                break;
            case "payment_intent.canceled":
                // 支付取消的逻辑
                break;
            // ... 其他事件类型
            default:
                log.info("Unhandled event type: {}", event.getType());
        }
    }

}

